"use strict";

import Base from './base.js';

export default class extends Base {
	// 获取员工信息列表
	async getuserlistAction(){
		let userlist = await this.model('or_app_user').where({shopid:this.shop_userinfo.departmentid}).select();
		return this.json(userlist);
	}

	// 添加员工基本工资
	async addbasepayAction(){
		let data = JSON.parse(this.post('data'));
		if (data.data.length) {
			for (var i = 0, len = data.data.length; i < len; i++) {
				data.data[i].addtime = Math.round(new Date().valueOf()/1000);
			}
			let res = await this.model('or_shop_userbasepay').addMany(data.data);
			return res?this.success({info:'添加成功'}):this.fail({data:102,info:'添加失败'});
		} else {
			let up1 = await this.model('or_shop_userbasepay').updateMany(data.basepay);
			return up1?this.success({info:'更新成功'}):this.fail({data:102,info:'更新失败'});
		}
	}

	// 获取当前员工工资信息（销售提成、服务提成、奖金提成、缺勤扣除等）
	async getpayAction(){
		let userid = this.post('userid');

		// 获取当月的起始时间和结束时间
		let times = JSON.parse(this.post('time'))
		
		let begintime = Math.floor(new Date().setHours(0,0,0,0)/1000), endtime = Math.floor(new Date().setHours(0,0,0,0)/1000) + 86400
		if (times && (times[0] != null && times[1] != null)) {
			begintime = Math.floor(new Date(times[0]).setHours(0,0,0,0)/1000)
			endtime = Math.floor(new Date(times[1]).setHours(0,0,0,0)/1000) + 86400
 		}

		let where = {
			userid: userid,
			time: {'>=': begintime, '<': endtime}
		}
		let list = await this.model('or_shop_userbasepay').where(where).select()
		return this.json(list);
	}

	// 给员工添加提成金额、指标金额、奖励金额、补贴金额、扣除金额
	async addpayAction(){
		let data = JSON.parse(this.post('data'));
		data.addtime = Math.round(new Date().valueOf()/1000);
		let res = await this.model('or_shop_userbasepay').add(data);
		return res?this.success('添加成功'):this.fail('添加失败');
	}

	// 删除员工工资信息
	async delpayAction(){
		let id = this.post('id');
		let res = await this.model('or_shop_userbasepay').where({id:id}).delete();
		return res?this.success({info:'删除成功'}):this.fail({info:'删除失败'});
	}

	// 编辑员工基本工资信息
	async editbasepayAction(){
		let data = JSON.parse(this.post('data'));
		if (data.userid) {
			let res = await this.model('or_shop_userbasepay').where({userid:data.userid, year:data.year, month:data.month, category:1, type:['IN',[1,2]]}).select();
			return this.json(res);
		} else {
			console.log(data);
			let zhicheng = await this.model('or_shop_userbasepay').where({id:data.tp1.id}).update({money:data.tp1.money});
			let zeren = await this.model('or_shop_userbasepay').where({id:data.tp2.id}).update({money:data.tp2.money});
			return zhicheng&&zeren?this.success({info:'修改成功'}):this.fail({data:102, info:'修改失败'});
		}
	}

	// 获取当前店家收付款帐号
	async getaccountlistAction(){
		let accountlist = await this.model('or_shop_account').where({departmentid:this.shop_userinfo.departmentid}).select();
		return this.json(accountlist);
	}

	// 结算员工工资
	async jiesuanAction(){
		let data = JSON.parse(this.post('data'));
		let addcost = data.addcost, addacco = data.addacco, accid = data.accid;
		let shopid = this.shop_userinfo.departmentid;
		let addtime = Math.round(new Date().valueOf()/1000);

		let model = this.model('or_shop_cost');
		await model.transaction(async () => {
			try {
				addcost.shopid = shopid;
				addcost.addtime = addtime;
				let is_cost = await model.add(addcost);
				if (!is_cost) {
					await model.rollback();
					return this.fail('结算失败1');
				}

				let is_acco = await this.model('or_shop_account').db(model.db()).where({id:accid}).decrement('balance',addcost.costmoney);
				if (think.isEmpty(is_acco)) {
					await model.rollback();
					return this.fail('结算失败2');
				}

				addacco.departmentid = shopid;
				addacco.orderid = is_cost;
				addacco.addtime = addtime;

				let is_log = await this.model('or_shop_accountlog').db(model.db()).add(addacco);
				if (is_log) {
					await model.commit();
					return this.success('结算成功');
				} else {
					await model.rollback();
					return this.fail('结算失败3');
				}
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('结算失败');
			}
		})
	}


	async insertuserpayAction () {
		let data = JSON.parse(this.post('data'))

		// 结账了就不能添加
		let unix = new Date(data.time)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth
		let jiesuandate = nYear + '' + nMonth

		let ishave = await this.model('or_shop_usergongzi').where({userid: data.userid, jiesuandate: jiesuandate}).find()

		if (!think.isEmpty(ishave)) {
			return this.fail('当前月份已经结算！')
		}

		// 写入数据库
		// 职称底薪和责任底薪只能添加一次
		if (data.category == 1) {
			let unix = new Date(data.time);
			let nYear = unix.getFullYear();
			let nMonth = unix.getMonth();

			let starttime  = Math.floor(new Date(nYear, nMonth, 1).getTime()/1000)
			let endtime = Math.floor(new Date(nYear, nMonth + 1, 1).getTime()/1000)
			let where = {
				category: data.category,
				type: data.type,
				userid: data.userid,
				time: {'>=': starttime, '<': endtime}
			}
			let ishave = await this.model('or_shop_userbasepay').where(where).find()
			if (!think.isEmpty(ishave)) {
				return this.fail('当月改底薪已经存在！')
			}
		}	

		data.time = Math.round(new Date(data.time).valueOf()/1000)
		data.addtime = Math.round(new Date().valueOf()/1000)

		let res = await this.model('or_shop_userbasepay').add(data)
        return res ? this.success({info:'操作成功'}) : this.fail({data:102, info:'操作失败'})
	}


	async deleteuserpayAction () {
		let row = JSON.parse(this.post('row'))

		// 判断是否已经结算
		let unix = new Date(row.time * 1000)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth
		let jiesuandate = nYear + '' + nMonth

		let ishave = await this.model('or_shop_usergongzi').where({userid: row.userid, jiesuandate: jiesuandate}).find()

		if (!think.isEmpty(ishave)) {
			return this.fail('当前月份已经结算！')
		}

		let res = await this.model('or_shop_userbasepay').where({id: row.id}).delete()
		return res ? this.success('操作成功') : this.fail('操作失败')
	}

	async jiesuangongziAction () {
		let data = JSON.parse(this.post('data'));
		let shopid = this.shop_userinfo.departmentid;
		let addtime = Math.round(new Date().valueOf()/1000);

		let unix = new Date(data.jiesuan.month)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth

		let jiesuantime = Math.floor(unix.getTime()/1000)
		let jiesuandate = nYear + '' + nMonth

		// 判断是否已经结算
		let isjiesuan = await this.model('or_shop_usergongzi').where({userid: data.user.id, shopid: shopid, jiesuandate: jiesuandate}).find()

		if (!think.isEmpty(isjiesuan)) {
			return this.fail('当前月份已经结算！')
		}
	
		let model = this.model('or_shop_cost');
		await model.transaction(async () => {
			try {	
				let costdata = {
					costtypeid: data.jiesuan.zhichutype,
					type: 2,
					costmoney: data.jiesuan.money,
					userid: data.user.id,
					shopid: shopid,
					bumenid: data.user.bumenid,
					xiaozuid: data.user.xiaozuid,
					fydate: Math.round(new Date(data.jiesuan.month).valueOf()/1000),
					remarks: data.jiesuan.remarks,
					addtime: addtime,
					accountid: data.jiesuan.zhanghu
				}

				let rescost = await model.add(costdata)

				// 结算账户金额减少

				let resaccount = await this.model('or_shop_account')
				.db(model.db())
				.where({id:data.jiesuan.zhanghu})
				.decrement('balance', data.jiesuan.money)

				let accountlogdata = {
					departmentid: shopid,
					accountid: data.jiesuan.zhanghu,
					ordertype: 'ZCD',
					orderid: rescost,
					money: data.jiesuan.money,
					addtime: addtime
				}

				let resaccountlog = await this.model('or_shop_accountlog').db(model.db()).add(accountlogdata)

				// 写入用户工资
				let gongzidata = {
					departmentid: shopid,
					shopid: shopid,
					userid: data.user.id,
					money: data.jiesuan.money,
					jiesuantime: jiesuantime,
					jiesuandate: jiesuandate,
					addtime: addtime,
					orderid: rescost
				}

				let resgongzi = await this.model('or_shop_usergongzi').db(model.db()).add(gongzidata)
	
				if (rescost && resaccount && resaccountlog && resgongzi) {
					await model.commit()
					return this.success('结算成功')
				} else {
					await model.rollback()
					return this.fail('结算失败')
				}
			} catch(e) {
				console.log(e)
				await model.rollback()
				return this.fail('结算失败')
			}
		})
	}
	// 获取员工工资信息
	async getuesrpaylistAction () {
		
		// 获取传入的起始时间和结束时间
		let page = JSON.parse(this.post('page'))
		let shopid = this.shop_userinfo.departmentid;

		let where = {
			'u.shopid': shopid,
			'u.isdisable': page.zt,
			'u.username|u.name|u.worknum': ['like','%'+page.search+'%']
		}

		let begintime = Math.floor(new Date().setHours(0,0,0,0)/1000), endtime = Math.floor(new Date().setHours(0,0,0,0)/1000) + 86400
		if (page.times && (page.times[0] != null && page.times[1] != null)) {
			begintime = Math.floor(new Date(page.times[0]).setHours(0,0,0,0)/1000)
			endtime = Math.floor(new Date(page.times[1]).setHours(0,0,0,0)/1000) + 86400
 		}

		let ulist = await this.model().query('SELECT u.id,u.name,u.worknum,u.addtime,IFNULL(t.xianjinyeji,0) as xjyj,IFNULL(t.xianjinticheng,0) AS xjtc,IFNULL(t.kahaoyeji,0) AS khyj,IFNULL(t.kahaoticheng,0) AS khtc,IFNULL(p.dixin,0) AS dixin,IFNULL(t.shougongticheng,0) as sgtc, IFNULL(t.qitaticheng,0) as qttc,IFNULL(p.ticheng,0) AS ticheng,IFNULL(p.zhibiao,0) AS zhibiao,IFNULL(p.jiangjin,0) AS jiangjin,IFNULL(p.butie,0) AS butie,IFNULL(p.kouchu,0) AS kouchu FROM `think_or_app_user` AS u LEFT JOIN (SELECT b.userid,b.time,sum(if(category = 1, money, 0)) as dixin,sum(if(category = 2, money, 0)) as ticheng, sum(if(category = 3, money, 0)) as zhibiao, sum(if(category = 4, money, 0)) as jiangjin, sum(if(category = 5, money, 0)) as butie, sum(if(category = 6, money, 0)) as kouchu FROM `think_or_shop_userbasepay` AS b LEFT JOIN `think_or_app_user` AS a ON a.id = b.userid WHERE a.shopid='+shopid+' AND b.time>='+begintime+' AND b.time<'+endtime+' GROUP BY b.userid) AS p ON p.userid = u.id LEFT JOIN (SELECT y.userid,y.addtime,sum(y.xianjinyeji) as xianjinyeji,sum(y.kahaoyeji) as kahaoyeji,sum(y.xianjinticheng) as xianjinticheng,sum(y.kahaoticheng) as kahaoticheng,sum(y.shougongticheng) as shougongticheng, sum(y.qitaticheng) as qitaticheng FROM `think_or_shop_yejiticheng` AS y LEFT JOIN `think_or_app_user` AS e ON e.id = y.userid WHERE y.addtime>='+begintime+' AND y.addtime<'+endtime+' AND y.shopid='+shopid+' GROUP BY y.userid) AS t ON u.id = t.userid WHERE u.shopid = '+shopid+' AND u.isdisable='+page.zt+' AND ((u.username LIKE "%'+page.search+'%") OR (u.name LIKE "%'+page.search+'%") OR (u.worknum LIKE "%'+page.search+'%")) LIMIT '+(page.pages-1)*page.limits+', '+page.limits);

		let counts = await this.model('or_app_user')
				.alias('u')
				.field('a.id')
				.join('`think_or_shop_userbasepay` a on a.userid=a.id and a.time>='+begintime+' and a.time<'+endtime)
				.where(where)
				.group('u.id')
				.select();

		let data = {
			data: ulist,
			count: counts.length
		}

		return this.json(data)
	}

	// 获取员工具体月份的工资
	async getmonthgongziAction () {
		let month = this.post('month')
		let userid = this.post('userid')

		let nowdata = new Date(month)
		let begintime = Math.floor(new Date(nowdata.getFullYear(), nowdata.getMonth(), 1, 0, 0, 0)/1000)
		let endtime = Math.floor(new Date(nowdata.getFullYear(), nowdata.getMonth() + 1, 1, 0, 0, 0)/1000)

		let money = await this.model('or_shop_userbasepay')
		.field('sum(if(category = 1, money, 0)) as dixin,sum(if(category = 2, money, 0)) as ticheng,sum(if(category = 3, money, 0)) as zhibiao,sum(if(category = 4, money, 0)) as jiangjin,sum(if(category = 5, money, 0)) as butie,sum(if(category = 6, money, 0)) as kouchu')
		.where({userid: userid, time: {'>=': begintime, '<': endtime}})
		.group('userid')
		.select()

		let gongzi = money[0] ? money[0] : {
			dixin: 0,
			ticheng: 0,
			zhibiao: 0,
			jiangjin: 0,
			butie: 0,
			kouchu: 0
		}
		return this.json(gongzi)
	}
}